<template>
  <div class="container">
    <!-- 添加页面导航 -->
    <PageNavigation pageTitle="房源分配管理" />
    
    <div class="page-header">
      <h2>房源分配管理</h2>
      <p>分配房源给经纪人进行审核和管理</p>
    </div>

    <!-- 待分配房源区域 -->
    <div class="unassigned-section">
      <div class="section-header">
        <h3>待分配房源 <small class="status-note">(经纪人未指定的房源)</small></h3>
        <el-button type="primary" size="small" @click="refreshUnassignedHouses">刷新列表</el-button>
      </div>
      
      <el-table :data="pendingHouses" style="width: 100%" v-loading="loadingUnassigned" class="mt-2">
        <el-table-column type="index" width="50" />
        <el-table-column prop="houseId" label="房源ID" width="80" />
        <el-table-column prop="title" label="房源标题" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="status" label="房源状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="上传时间" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleAssignPending(scope.row)">分配</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="pendingHouses.length === 0 && !loadingUnassigned" class="empty-tip">
        <el-empty description="暂无待分配房源" :image-size="80">
          <template #description>
            <p>暂无待分配房源(未指定经纪人的房源)</p>
          </template>
        </el-empty>
      </div>
    </div>

    <!-- 搜索表单 -->
    <div class="section-divider"></div>
    <div class="section-header mt-4">
      <h3>分配记录管理</h3>
    </div>
    
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="房源ID">
        <el-input v-model="queryParams.houseId" placeholder="请输入房源ID" clearable />
      </el-form-item>
      <el-form-item label="房源状态">
        <el-select v-model="queryParams.houseStatus" placeholder="房源状态" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="待审核" value="0"></el-option>
          <el-option label="在售" value="1"></el-option>
          <el-option label="已售" value="2"></el-option>
          <el-option label="下架" value="3"></el-option>
          <el-option label="审核未通过" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="经纪人">
        <el-input v-model="queryParams.agentName" placeholder="请输入经纪人姓名" clearable />
      </el-form-item>
      <el-form-item label="分配状态">
        <el-select v-model="queryParams.status" placeholder="分配状态" clearable>
          <el-option label="无效" value="0" />
          <el-option label="有效" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="success" @click="handleAssign">分配房源</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="assignList" style="width: 100%" v-loading="loading">
      <el-table-column type="index" width="50" />
      <el-table-column prop="assignId" label="分配ID" width="80" />
      <el-table-column prop="houseId" label="房源ID" width="80" />
      <el-table-column prop="houseTitle" label="房源标题" />
      <el-table-column prop="agentId" label="经纪人ID" width="80" />
      <el-table-column prop="agentName" label="经纪人" />
      <el-table-column prop="assignType" label="分配类型">
        <template #default="scope">
          <el-tag :type="scope.row.assignType === '1' ? 'info' : 'success'">
            {{ scope.row.assignType === '1' ? '自动分配' : '手动指定' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="assignTime" label="分配时间" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'danger' : 'success'">
            {{ scope.row.status === '0' ? '无效' : '有效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)" v-if="scope.row.status === '1'">编辑</el-button>
          <el-button size="small" type="danger" @click="handleCancel(scope.row)" v-if="scope.row.status === '1'">取消分配</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 分配房源对话框 -->
    <el-dialog title="分配房源" v-model="assignDialogVisible" width="500px">
      <el-form :model="assignForm" label-width="100px" :rules="assignRules" ref="assignFormRef">
        <el-form-item label="选择房源" prop="houseId">
          <el-select v-model="assignForm.houseId" placeholder="请选择待分配的房源" style="width: 100%" 
            @change="handleHouseSelected" filterable remote :remote-method="searchHouses" 
            :loading="loadingHouses">
            <el-option 
              v-for="item in pendingHousesSelect" 
              :key="item.houseId" 
              :label="`${item.title} (${item.houseId})`" 
              :value="item.houseId" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择经纪人" prop="agentId">
          <el-select v-model="assignForm.agentId" placeholder="请选择经纪人" style="width: 100%"
            filterable remote :remote-method="searchAgents" :loading="loadingAgents">
            <el-option
              v-for="agent in agentList"
              :key="agent.agentId"
              :label="`${agent.realName} (${agent.agentId})`"
              :value="agent.agentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="assignForm.remark" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssign" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageNavigation from '@/components/common/PageNavigation.vue'
import { getAssignList, getHouseList, getAgentList, assignHouse, cancelAssign, getUnassignedHouses } from '@/api/admin/assign'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  houseId: '',
  houseStatus: '',
  agentName: '',
  status: '',
  pageNum: 1,
  pageSize: 10
})

const assignList = ref([])
const total = ref(0)
const loading = ref(false)
const submitting = ref(false)

// 分配相关
const assignDialogVisible = ref(false)
const assignFormRef = ref(null)
const assignForm = reactive({
  houseId: '',
  agentId: '',
  remark: ''
})

const assignRules = {
  houseId: [{ required: true, message: '请选择房源', trigger: 'change' }],
  agentId: [{ required: true, message: '请选择经纪人', trigger: 'change' }]
}

const pendingHouses = ref([])         // 待分配房源列表（显示在顶部）
const pendingHousesSelect = ref([])   // 下拉选择框中的待分配房源
const agentList = ref([])
const loadingHouses = ref(false)
const loadingAgents = ref(false)
const loadingUnassigned = ref(false)  // 顶部待分配房源列表加载状态

// 初始化页面
onMounted(() => {
  fetchAssignList()
  fetchUnassignedHouses()
})

// 获取分配列表
const fetchAssignList = async () => {
  loading.value = true
  try {
    console.log('请求参数:', queryParams)
    const res = await getAssignList(queryParams)
    console.log('响应结果:', res)
    if (res.code === 200) {
      assignList.value = res.data.records || res.data
      total.value = res.data.total || res.data.length
    } else {
      ElMessage.error(res.msg || '获取分配列表失败')
    }
  } catch (error) {
    console.error('获取分配列表失败详细信息:', error)
    if (error.response) {
      console.error('错误响应数据:', error.response.data)
      console.error('错误状态码:', error.response.status)
    }
    ElMessage.error(`获取分配列表失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 获取待分配的房源列表
const fetchUnassignedHouses = async () => {
  loadingUnassigned.value = true
  try {
    const res = await getUnassignedHouses()
    console.log('待分配房源响应:', res)
    if (res.code === 200) {
      pendingHouses.value = res.data
      pendingHousesSelect.value = [...res.data] // 复制一份给选择框使用
    } else {
      ElMessage.error(res.msg || '获取待分配房源失败')
    }
  } catch (error) {
    console.error('获取待分配房源失败:', error)
    ElMessage.error('获取待分配房源失败')
  } finally {
    loadingUnassigned.value = false
  }
}

// 刷新待分配房源列表
const refreshUnassignedHouses = () => {
  fetchUnassignedHouses()
  ElMessage.success('待分配房源列表已刷新')
}

// 搜索房源
const searchHouses = async (query) => {
  if (query) {
    loadingHouses.value = true
    try {
      const res = await getHouseList({ title: query })
      if (res.code === 200) {
        // 过滤出未分配的房源
        const data = res.data.records || res.data
        pendingHousesSelect.value = data.filter(item => !item.agentId)
      }
    } catch (error) {
      console.error('搜索房源失败:', error)
    } finally {
      loadingHouses.value = false
    }
  } else {
    // 如果查询为空，获取所有未分配房源
    pendingHousesSelect.value = [...pendingHouses.value]
  }
}

// 搜索经纪人
const searchAgents = async (query) => {
  loadingAgents.value = true
  try {
    console.log('搜索经纪人:', query)
    const res = await getAgentList({ realName: query })
    console.log('经纪人搜索结果:', res)
    if (res.code === 200) {
      agentList.value = res.data
    } else {
      console.error('经纪人搜索响应错误:', res)
    }
  } catch (error) {
    console.error('搜索经纪人失败:', error)
    if (error.response) {
      console.error('错误响应数据:', error.response.data)
    }
  } finally {
    loadingAgents.value = false
  }
}

// 待分配房源的分配按钮处理
const handleAssignPending = (row) => {
  assignForm.houseId = row.houseId
  assignForm.agentId = ''
  assignForm.remark = row.title // 默认使用房源标题作为备注
  assignDialogVisible.value = true
  
  // 加载经纪人列表
  loadingAgents.value = true
  getAgentList({}).then(res => {
    if (res.code === 200) {
      agentList.value = res.data
    }
    loadingAgents.value = false
  }).catch(err => {
    console.error('加载经纪人列表失败:', err)
    loadingAgents.value = false
  })
}

// 房源选择事件
const handleHouseSelected = async (houseId) => {
  // 可以在这里获取房源详情，验证是否已分配等
  const selectedHouse = pendingHousesSelect.value.find(h => h.houseId === houseId)
  if (selectedHouse) {
    assignForm.remark = selectedHouse.title // 默认使用房源标题作为备注
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchAssignList()
}

// 重置
const resetQuery = () => {
  queryParams.houseId = ''
  queryParams.houseStatus = ''
  queryParams.agentName = ''
  queryParams.status = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchAssignList()
}

// 分页页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchAssignList()
}

// 分配房源
const handleAssign = async () => {
  assignForm.houseId = ''
  assignForm.agentId = ''
  assignForm.remark = ''
  assignDialogVisible.value = true
  
  // 加载初始数据
  loadingHouses.value = true
  loadingAgents.value = true
  try {
    // 获取未分配的房源和正常状态的经纪人
    const [housesRes, agentsRes] = await Promise.all([
      getUnassignedHouses(),
      getAgentList({})
    ])
    
    console.log('未分配房源:', housesRes)
    console.log('经纪人列表:', agentsRes)
    
    if (housesRes.code === 200) {
      pendingHousesSelect.value = housesRes.data
    }
    
    if (agentsRes.code === 200) {
      agentList.value = agentsRes.data
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    if (error.response) {
      console.error('错误响应数据:', error.response.data)
    }
  } finally {
    loadingHouses.value = false
    loadingAgents.value = false
  }
}

// 提交分配
const submitAssign = async () => {
  if (!assignFormRef.value) return
  
  await assignFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      const res = await assignHouse(assignForm.houseId, assignForm.agentId, assignForm.remark)
      if (res.code === 200) {
        ElMessage.success('房源分配成功')
        assignDialogVisible.value = false
        
        // 刷新数据
        fetchAssignList()
        fetchUnassignedHouses() // 更新待分配房源列表
      } else {
        ElMessage.error(res.msg || '分配失败')
      }
    } catch (error) {
      console.error('分配房源失败:', error)
      ElMessage.error('分配房源失败: ' + (error.message || ''))
    } finally {
      submitting.value = false
    }
  })
}

// 编辑分配
const handleEdit = (row) => {
  assignForm.houseId = row.houseId
  assignForm.agentId = row.agentId
  assignForm.remark = row.remark
  assignDialogVisible.value = true
}

// 取消分配
const handleCancel = (row) => {
  ElMessageBox.confirm(`确定要取消房源"${row.houseTitle}"分配给"${row.agentName}"的记录吗？取消后房源将变为待分配状态。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await cancelAssign(row.houseId, row.agentId)
      if (res.code === 200) {
        ElMessage.success('取消分配成功，房源已变为待分配状态')
        
        // 刷新数据
        fetchAssignList()
        fetchUnassignedHouses() // 更新待分配房源列表
      } else {
        ElMessage.error(res.msg || '取消分配失败')
      }
    } catch (error) {
      console.error('取消分配失败:', error)
      ElMessage.error('取消分配失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 获取房源状态类型
const getStatusType = (status) => {
  switch (status) {
    case '0':
      return 'danger'
    case '1':
      return 'success'
    case '2':
      return 'warning'
    case '3':
      return 'info'
    case '4':
      return 'danger'
    default:
      return ''
  }
}

// 获取房源状态标签
const getStatusLabel = (status) => {
  switch (status) {
    case '0':
      return '待审核'
    case '1':
      return '在售'
    case '2':
      return '已售'
    case '3':
      return '下架'
    case '4':
      return '审核未通过'
    default:
      return '未知状态'
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  margin: 0 0 10px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-header h3 {
  font-size: 18px;
  margin: 0;
  color: #333;
}

.section-divider {
  height: 1px;
  background-color: #e0e0e0;
  margin: 20px 0;
}

.unassigned-section {
  margin-bottom: 30px;
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.search-form {
  margin-bottom: 20px;
  background: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mt-2 {
  margin-top: 8px;
}

.mt-4 {
  margin-top: 16px;
}

.status-note {
  font-size: 12px;
  font-weight: normal;
  color: #909399;
}

.empty-tip {
  padding: 20px 0;
  text-align: center;
}
</style> 